import { buildCartProductKey, ICartProduct, IProductWithSelected, IResult } from "models";

/**jest的模块化是隔离的? 导致mock里使用变量存储无法实现数据互通, 本类暂时没用到, 使用的是jsdom里提供的本地存储环境*/
export class CartLocalStorage {

    /**mock时使用静态变量保存购物车中所有商品*/
    public static localCartProducts: ICartProduct[] = [];
    public static loadProducts(): IResult<ICartProduct[]> {
        return { success: true, data: CartLocalStorage.localCartProducts };
    }
    public static saveProducts(list: ICartProduct[]): IResult<null> {
        CartLocalStorage.localCartProducts = list;
        return { success: true, data: null };
    }
    public static clearProducts(): void {
        CartLocalStorage.saveProducts([]);
    }
    public static addProduct(product: IProductWithSelected) {
        let listRet = CartLocalStorage.loadProducts();
        if (!listRet.success) {
            console.error('购物车加载本地数据失败', listRet, '将使用全空购物车开始');
        }

        let cKey = buildCartProductKey(product);
        let list = listRet.success ? listRet.data : [];
        let cp = list.find(p => p.key === cKey);
        if (cp) {
            cp.quantity += 1;
        }
        else {
            cp = {
                ...product,
                key: cKey,
                quantity: 1,
            };
            list.push(cp);
        }
        CartLocalStorage.saveProducts(list);
    }
}